package com.itphy.socket;

import com.alibaba.fastjson.JSON;
import com.itphy.common.R;
import com.itphy.util.CookieUtil;
import com.itphy.util.RedisClient;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import com.itphy.common.mxqy.MessageMXQY;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@ServerEndpoint(value = "/itphy/websocket")
public class MXQYSocket implements Listener {

    @Override
    public void onOpen(Session session) {
        Map<String, Object> cookieMap = CookieUtil.getCookieMap(session);
        String token = (String) cookieMap.get("token");

    }

    @Override
    public void onMessage(Session session, Message message) throws IOException {
        Jedis jedis =null;
        try {
            MessageMXQY data=JSON.parseObject(message.bodyAsString(), MessageMXQY.class);
            jedis = RedisClient.getJedis();
            String list = jedis.get("MXQY::001");
            List<MessageMXQY> allData=null;
            if(Objects.isNull(list)){
                allData = new ArrayList<>();
            }else {
                allData= JSON.parseObject(list, List.class);
            }//存储时间1分钟
            allData.add(data);
            jedis.setex("MXQY::001", 180,JSON.toJSONString(allData));
            session.getOpenSessions().forEach(s -> {
                s.send(JSON.toJSONString(R.ok().data(data)));
            });
        }catch (Exception e){
            session.send(JSON.toJSONString(R.fail().msg("非法数据")));
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    @Override
    public void onClose(Session session) {

    }
}
